<script setup lang="ts">
import { uploadAPI } from '@/apis/common';
import { createEnterpriseAPI, getEnterpriseDetailAPI, getIndustryListAPI, updateEnterpriseAPI } from '@/apis/enterprise';
import { loginAPI } from '@/apis/user';
import {  type EnterpriseDetail, type EnterpriseParams, type EnterpriseParamsEdit, type Industry} from '@/types/enterprise';
import { Upload } from '@element-plus/icons-vue';
import { ElMessage, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';


const addForm = ref<EnterpriseParams>({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode: undefined, // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: '', // 营业执照url
  businessLicenseId: 0 // 营业执照id
}) 

// 行业
const industryList = ref<Industry[]>([])
const getIndustryList = async()=>{
  const res = await getIndustryListAPI()

  industryList.value = res.data
  
}
getIndustryList()


// 上传的文件
const fileList = ref<UploadUserFile[]>([])

// 自定义上传
const onUploadRequest = async (options:UploadRequestOptions)=>{
  console.log('options',options)
  // 1.准备FormData对象
  const fd = new FormData()
  // 2.根据后端要求准备字段
  fd.append('file',options.file)
  fd.append('type','businessLicense')
  // 3.调用接口上传文件
  const res = await uploadAPI(fd)
  // 保存营业执照url和id ，用于添加企业
  addForm.value.businessLicenseUrl=res.data.url
  addForm.value.businessLicenseId=res.data.id
  // 主动触发校验 通过会清除错误信息
  formRef.value?.validateField('businessLicenseUrl')
  // 4. 检查上传结果，并 return 存储到 response 属性中
  return res.data.url

  // // 保存已经上传的文件列表
  // fileList.value.push({name:File.name})

}

// 删除上传文件
const removeUpload = ()=>{
  addForm.value.businessLicenseUrl=''
  addForm.value.businessLicenseId=undefined
  // 主动触发 提醒用户
  formRef.value?.validateField('businessLicenseUrl')
}

const beforeUpload = (rawFile:UploadRawFile)=>{
    // 5M = 5 * 1024 * 1024
    if(rawFile.size > 5 *1021 *1024){

      ElMessage.error('文件过大,请上传5M以下的文件')
      return false
   }else if (['images/jpeg','image/png'].includes(rawFile.type)===false){
    ElMessage.error('文件格式不正确，请上传图片')
    return false
   }
   return true
}
// 表单校验规则
const addRules = ref<FormRules<EnterpriseParams>>({
  name:[
    
     {required:true,message:'请输入企业名称',trigger:'blur'},
    {min:2,max:20,message:'名称在2到20个字符之间',trigger:'blur'}
],
  legalPerson:[
  {required:true,message:'请输入法人',trigger:'blur'},
  ],
  registeredAddress:[
  {required:true,message:'请输入注册地址',trigger:'blur'},
  ],
  industryCode:[
  {required:true,message:'请选择行业',trigger:'change'},
  ],
  contact:[
  {required:true,message:'请输入企业联系人',trigger:'blur'},
  ],
  contactNumber:[
  {required:true,message:'请输入联系人电话',trigger:'blur'},
  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  businessLicenseUrl:[
  {required:true,message:'请上传营业执照',trigger:'blur'},
  ]
  
})

// 表单 企业信息
// Partical 泛型工具

// 用于表单提交时，整个表单校验
const formRef = ref<FormInstance>()

// 获取路由实例
const router = useRouter()
const submitLoading = ref(false)



// 确认提交
const onSubmit = async()=>{
  try{
    // 对表单进行校验，有id说明是编辑业务，无id说明是添加业务
    if(route.params.id){
      addForm.value.id = route.params.id as string
      const data: EnterpriseParamsEdit = {} as EnterpriseParamsEdit
      Object.assign(data, addForm.value)
      // 编辑业务
      await updateEnterpriseAPI(data)  
    }else{
      // 添加业务
      // 对整个表单进行校验
    await formRef.value?.validate()
    // 把按钮设置为加载状态，禁用提交，避免重复提交
    submitLoading.value = true
    // 提交表单数据给后端
    await createEnterpriseAPI(addForm.value)
      // 轻提示
      ElMessage.success('添加成功')
     // 返回上一页
      router.back()
    
    }
   
  
  }catch{
    // 恢复按钮状态
    submitLoading.value=false
  }
}

// 重置表单
const onReset =() =>{
  formRef.value?.resetFields()
}



// 获取企业数据
const getEnterpriseDetail = async () =>{
  const res = await getEnterpriseDetailAPI(route.params.id as string)
  console.log(res)
 
  //提取表单所需要的数据
  const {businessLicenseId,businessLicenseUrl,contact,contactNumber,
    industryCode,legalPerson,name,registeredAddress,id} =res.data

    addForm.value = {businessLicenseId,contact,contactNumber,
      businessLicenseUrl, industryCode,legalPerson,name,registeredAddress}
      // 单独处理图片数据
    fileList.value.push({ name: name, url: businessLicenseUrl })

}

// 路由
const route = useRoute()

// 如果路由有id，就调用接口获取企业详情
if(route.params.id){
  getEnterpriseDetail()
}

</script>

<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header :content="$route.params.id ?'编辑企业' :'添加企业'"  @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" :model="addForm" :rules="addRules" label-width="100px" >
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson" >
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业">
              
              <el-select v-model="addForm.industryCode" >
              <el-option v-for="item in industryList" :key="item.industryCode" :value="item.industryCode" :label="item.industryName"></el-option>
            </el-select>
          </el-form-item>
            <el-form-item label="企业联系人" prop="legalPerson">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl" >
            <el-upload  :http-request="onUploadRequest"  list-type="picture" :limit="1" v-model:file-list="fileList"
            :before-upload="beforeUpload"
            accept="..png,.jpg,.jpeg"
            @remove="removeUpload"
            >
              <el-button type="primary" :icon="Upload" v-if="fileList.length===0" >
                点击上传
              </el-button >
              <el-button type="success" disabled :icon="Upload" v-else >
                已上传
              </el-button >
                <template #tip>
                  <div class="el-upload__tip">
                    支持扩展名：.png .jpg .jpeg, 文件大小不得超过5M
                  </div>
                </template>
         
            </el-upload>
            </el-form-item>
          </el-form>
        </div>
        {{ fileList }}
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="onReset()">重置</el-button>
        <el-button type="primary" @click="onSubmit()" :loading="submitLoading" >确定</el-button>
      </div>
    </footer>
  </div>
</template>


<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>